﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using Microsoft.AspNet.SignalR;
using Pay.IService;
using Pay.TO;

namespace Pay.Token {
    public class MyHub : Hub {
        public static List<User> onlineUsers = new List<User>();
        DateTime startTime;
        DateTime endTime;
        private ISoupTaskService _iSoupTaskService { get; set; }
        /// <summary>
        /// 发送心跳包
        /// </summary>
        /// <param name="voip"></param>
        private void SendHeartBeat(string connid) {
            Clients.Client(connid).recieveHeartBeat(connid);
            // Clients.All.recieveHeartBeat(voip);
        }

        /// <summary>
        /// 接收心跳包
        /// </summary>
        /// <param name="id"></param>
        public void RecieveHeartBeat(long name, string connid) {
            var user = onlineUsers.Where(u => u.Voip == name).FirstOrDefault();
            if (user == null) return;
            user.Second = 0;

        }
        public void LoginIn(long voip) {
            var user = onlineUsers.Where(u => u.Voip == voip).FirstOrDefault();
            string connId = Context.ConnectionId;
            if (user == null) {
                startTime = DateTime.Now;

                user = new User {
                    Voip = voip,
                    Second = 0,

                };

                user.ConnectionIds.Add(connId);
                onlineUsers.Add(user);
                Console.WriteLine(user.Voip + "上线了");
                //Console.ReadLine();
                user.HeartBeatAction += () => {
                    SendHeartBeat(connId);
                };
                user.LogoutAction += () => {
                    LoginOut(voip);
                };
            } else {
                user.ConnectionIds.Add(connId);
                user.HeartBeatAction += () => {
                    SendHeartBeat(connId);
                };
                user.LogoutAction += () => {
                    LoginOut(user.Voip);
                };
                Console.WriteLine(user.Voip + "已经在线了");
                Console.ReadLine();
            }

        }
        /// <summary>
        /// 用户主动下线
        /// </summary>
        /// <param name="voip"></param>
        public void LoginOut(long voip) {
            endTime = DateTime.Now;
            var user = onlineUsers.Where(u => u.Voip == voip).FirstOrDefault();
            Console.WriteLine(user.Voip + " 下线了");
            onlineUsers.Remove(user);
            TimeSpan t = endTime - startTime;
            if (t.TotalSeconds - 30 > 60 * 2) {
                var obj = new { merchant_no = user.Voip };
                try {
              var result= _iSoupTaskService.TaskRecive(user.Voip, ETaskType.ViewMall).Result;
                } catch (Exception ex) {
                  
                }

            }
        }

        private void UserLoginOut(long voip) {
            LoginOut(voip);
        }
    }
    public class User {


        public long Voip { get; set; }
        public int Second { get; set; }
        public List<string> ConnectionIds { get; set; }

        private readonly Timer timer;//定时器
        /// <summary>
        /// 间隔秒数
        /// </summary>
        private int During = 30;

        /// <summary>
        /// 掉线后的操作
        /// </summary>
        public event Action LogoutAction;

        /// <summary>
        /// 发送心跳包的动作
        /// </summary>
        public event Action HeartBeatAction;
        public User() {
            ConnectionIds = new List<string>();
            Second = 0;
            if (timer == null) {
                timer = new Timer(1000);
            }
            timer.Start();//计时器启动
            timer.Elapsed += (sender, args) => {
                Second++;
                //每5s发送一次心跳包
                if (Second % 5 == 0) {
                    if (HeartBeatAction != null) {
                        HeartBeatAction();
                    }
                }
                if (Second >= During) {
                    timer.Stop();
                    timer.Dispose();
                    //用户30s无心跳包应答，则视为掉线，会抛出事件，然后处理用户掉线动作。
                    if (LogoutAction != null) {
                        LogoutAction();
                    }
                }
            };


        }
    }
}